﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DocumentTransferServiceTest
{

    class ConfigMgr
    {
        private static string _keyServer = "server";

        public static string GetServer()
        {
            return ConfigurationManager.AppSettings[_keyServer];
        }

        public static void Save(string server)
        {
            string configFile = Application.ExecutablePath + ".config";

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add(_keyServer, server);

            SaveAppSettings(configFile, dict);
        }

        /// <summary>
        /// 打开并获取表示指定配置文件的 Configuration 对象。
        /// </summary>
        /// <param name="configFile"></param>
        /// <returns></returns>
        private static Configuration OpenConfigurationFile(string configFile)
        {

            if (string.IsNullOrWhiteSpace(configFile))
                return null;

            configFile = configFile.Trim();

            if (File.Exists(configFile) == false)
                return null;

            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = configFile;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);


            return config;
        }

        /// <summary>
        /// 把键值对集合保存到指定的应用程序配置文件中。
        /// </summary>
        /// <param name="configFile"></param>
        /// <param name="configValues"></param>
        private static void SaveAppSettings(string configFile, Dictionary<string, string> configValues)
        {
            if (configValues == null || configValues.Count == 0)
                return;

            Configuration config = OpenConfigurationFile(configFile);
            if (config == null)
            {
                string msg = string.Format("打开配置文件 {0} 时遇到错误。", configFile);
                throw new ConfigurationErrorsException(msg);
            }

            KeyValueConfigurationCollection settings = config.AppSettings.Settings;
            if (settings != null)
            {
                bool needSave = false;

                foreach (KeyValuePair<string, string> configValue in configValues)
                {
                    string key = configValue.Key;
                    if (string.IsNullOrWhiteSpace(key))
                        throw new ArgumentNullException("key", "配置文件中 key 不能为空。");

                    string value = configValue.Value;
                    if (value == null)
                        value = string.Empty;

                    if (settings[key] == null)
                    {
                        settings.Add(key, value);
                        needSave = true;
                    }
                    else if (settings[key].Value != value)
                    {
                        settings[key].Value = value;
                        needSave = true;
                    }
                }

                if (needSave)
                    config.Save(ConfigurationSaveMode.Minimal);
            }

        }
    }
}
